﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Linq;

namespace ST.Buz.Service
{
	public partial class ServiceSysUserAddress
	{
		private readonly IServiceSysLog serviceSysLog;

		public ServiceSysUserAddress(BuzContext ctx,
			IServiceSysLog _serviceSysLog,
			ILogger<ServiceSysUserAddress> log)
		{
			serviceSysLog = _serviceSysLog;

			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 获取分页数据
		/// </summary>
		/// <param name="pageNum"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public PageData GetPageList(VMS_Sys_UserAddress searchModel)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();
				var query = from m in context.SysUserAddress
							select m;
				if (!string.IsNullOrWhiteSpace(searchModel.name))
				{
					query = query.Where(m => m.Name.Contains(searchModel.name));
				}
				if (!string.IsNullOrWhiteSpace(searchModel.mobile))
				{
					query = query.Where(m => m.Mobile.Contains(searchModel.mobile));
				}
				if (searchModel.userid > 0)
				{
					query = query.Where(m => m.UserID == searchModel.userid);
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				var lst = result.LoadQuery(query);
				if (searchModel.encrypt && lst != null && lst.Count > 0)
				{
					foreach (Sys_UserAddress m in lst)
					{
						m.Mobile = !string.IsNullOrEmpty(m.Mobile) && m.Mobile.Length > 7 ? m.Mobile.Substring(0, 3) + "****" + m.Mobile.Substring(m.Mobile.Length - 4) : m.Mobile;
					}
				}
				result.list = lst;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		/// <summary>
		/// 新增或修改当前用户的收货地址信息
		/// </summary>
		/// <param name="vm"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public int AddOrUpdate(Sys_UserAddress vm, UserSession sessionCurrent)
		{
			try
			{
				if (vm == null)
				{
					throw new BuzException("参数不能为空");
				}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户未登录或登录已过期");
				}

				DateTime dtNow = DateTime.Now;
				string ip = GetRequestIP();
				if (vm.Preferred)
				{
					SqlParameter[] paras = new SqlParameter[]{
						new SqlParameter("@Preferred",false),
						new SqlParameter("@UserID",sessionCurrent.UserID),
					};
					context.Database.ExecuteSqlRaw("UPDATE Sys_UserAddress SET Preferred=@Preferred WHERE UserID=@UserID", paras);
				}

				Sys_UserAddress model = null;
				if (vm.ID > 0)
				{
					model = context.SysUserAddress.SingleOrDefault(m => m.ID == vm.ID);
					if (model == null)
					{
						throw new BuzException("未找到相关信息");
					}
					if (model.UserID != sessionCurrent.UserID)
					{
						throw new BuzException("只能修改自己的地址信息");
					}

					serviceSysLog.Add(sessionCurrent, ip, "修改当前用户地址信息，原信息：", model, dtNow);

					//todo:更新信息
				}
				else
				{
					model.Type = (int)AddressType.收件地址;
					model.AddDate = dtNow;
					model.AddManID = sessionCurrent.UserID;
					model.AddManName = sessionCurrent.UserName;
					model.UserID = sessionCurrent.UserID;
					model.LastModifyDate = dtNow;
					model.LastModifyManID = sessionCurrent.UserID;
					model.LastModifyManName = sessionCurrent.UserName;

					context.SysUserAddress.Add(model);
				}

				context.SaveChanges();

				return model.ID;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (DbUpdateException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 删除当前用户指定的收货地址
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户未登录或登录已过期");
				}
				Sys_UserAddress modelOld = context.SysUserAddress.SingleOrDefault(m => m.ID == id);
				if (modelOld == null)
				{
					throw new BuzException("记录不存在");
				}
				if (modelOld.UserID != sessionCurrent.UserID)//非当前用户的地址信息不能删除
				{
					throw new BuzException("只能删除自己的地址信息");
				}

				DateTime dtNow = DateTime.Now;
				string ip = GetRequestIP();

				serviceSysLog.Add(sessionCurrent, ip, "删除当前用户指定的收货地址，收货人信息：", modelOld, dtNow);

				context.SysUserAddress.Remove(modelOld);
				context.SaveChanges();

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除对象信息出错");
				throw new BuzException("删除失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 获取指定或默认的收货地址
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public Sys_UserAddress GetDefaultAddress(UserSession sessionCurrent)
		{
			//todo:获取当前用户的默认地址
			throw new NotImplementedException();
		}
	}
}